package org.monster.context.core.headerfilter;

import org.monster.context.core.parameter.HttpResponse;
import org.monster.context.core.request.HttpRequest;
import org.monster.context.util.URIUtils;

import javax.servlet.*;
import java.io.IOException;

/**
 * 头路径过滤器
 *
 * @author Monster
 */
public class HeaderPathFilter implements HeaderFilter {

    /**
     * 解析 头
     *
     * @param request  请求
     * @param response 响应
     * @param chain    通道
     */
    @Override
    public void parseHeaders(HttpRequest request, HttpResponse response,
                             HeaderFilterChain chain) {
        String requestURI = request.getRequestURI();
        if (requestURI != null) {
            setServletPath(request, requestURI);
            setContextPath(request, requestURI);

        }
    }

    /**
     * 解析 头
     *
     * @param request  请求
     * @param response 响应
     * @param chain    通道
     */
    public void parseHeaders(HttpRequest request, HttpResponse response,
                             FilterChain chain) {
        String requestURI = request.getRequestURI();
        if (requestURI != null) {
            setServletPath(request, requestURI);
            setContextPath(request, requestURI);
        }
    }

    /**
     * 设置 服务者路径
     *
     * @param request    请求
     * @param requestURI 请求Uri
     */
    private void setServletPath(HttpRequest request, String requestURI) {
        String servletPath = URIUtils.allEndsWithURI(requestURI);
        int index = servletPath.lastIndexOf('?');
        if (index != -1) {
            servletPath = servletPath.substring(0, index);
        }
        request.setServletPath(servletPath);
    }

    /**
     * 设置 上下文路径
     *
     * @param request    请求
     * @param requestURI 请求Uri
     */
    private void setContextPath(HttpRequest request, String requestURI) {
        String[] split = requestURI.split("/");
        if (split.length > 2) {
            String contextPath = URIUtils.startWithURI(requestURI);
            request.setContextPath("/" + contextPath);
        }

    }

    /**
     * 做 过滤
     *
     * @param request  请求
     * @param response 响应
     * @param chain    通道
     * @throws IOException      输入输出异常
     * @throws ServletException 服务者异常
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpRequest httpRequest = (HttpRequest) request;
        HttpResponse httpResponse = (HttpResponse) response;
        parseHeaders(httpRequest, httpResponse, chain);
        chain.doFilter(request, response);
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
    }

    /**
     * 初始化
     *
     * @param arg0 过滤器配置
     * @throws ServletException 服务者异常
     */
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}
